package com.shenyue.nbtownlet.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.google.android.flexbox.FlexboxLayout;
import com.hitomi.glideloader.GlideImageLoader;
import com.hitomi.tilibrary.style.progress.ProgressPieIndicator;
import com.hitomi.tilibrary.transfer.TransferConfig;
import com.hitomi.tilibrary.transfer.Transferee;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.shenyue.nbtownlet.R;
import com.shenyue.nbtownlet.adapter.LabelListViewAdapter;
import com.shenyue.nbtownlet.base.BaseActivity;
import com.shenyue.nbtownlet.databinding.ActivityNewDissertationBinding;
import com.shenyue.nbtownlet.databinding.ImagePartItemRemoveBinding;
import com.shenyue.nbtownlet.event.BaseListener;
import com.shenyue.nbtownlet.location.BDLocationManager;
import com.shenyue.nbtownlet.model.AppContactsModel;
import com.shenyue.nbtownlet.model.AppDissertationModel;
import com.shenyue.nbtownlet.model.AppLoginModel;
import com.shenyue.nbtownlet.model.AppModel;
import com.shenyue.nbtownlet.model.FileUploadModel;
import com.shenyue.nbtownlet.util.DensityUtil;
import com.shenyue.nbtownlet.util.GlideUtil;
import com.shenyue.nbtownlet.util.GpsUtil;
import com.shenyue.nbtownlet.util.StringUtil;
import com.trycatch.mysnackbar.Prompt;
import com.trycatch.mysnackbar.TSnackbar;

import java.util.ArrayList;
import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * 专题新增
 */

public class NewDissertationActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener, BaseListener {
    private ActivityNewDissertationBinding binding;
    private Context mContext;
    private Handler mHandler = new Handler();
    private int[] wh;
    private List<String> addImages = new ArrayList<>();
    private List<ImageView> addImageViews = new ArrayList<>();
    private static final int REQUEST_CODE_SELECT = 100;
    // 语音听写UI
    private RecognizerDialog mIatDialog;
    private LabelListViewAdapter countyListViewAdapter, streetListViewAdapter, iPIdListViewAdapter;
    private BDLocationManager bdLocationManager = new BDLocationManager();
    private TSnackbar snackBar;
    private boolean isLoading = false;
    private boolean imageLoading = false;
    private int imagePosition = 0;

    private JSONObject paramData;//表单初始数据
    private Transferee transferee;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.activity_new_dissertation);
        setActionBar(true, "新增专题");
        mContext = this;
        transferee = Transferee.getDefault(mContext);

        binding.countyPart.setOnClickListener(this);
        binding.streetPart.setOnClickListener(this);
        binding.county.setParentScrollView(binding.scrollView);
        binding.street.setParentScrollView(binding.scrollView);
        binding.iPIdPart.setOnClickListener(this);
        binding.iPId.setParentScrollView(binding.scrollView);
        binding.btnAdd.setOnClickListener(this);

        wh = DensityUtil.getWH(this, 2, 30);
        FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(wh[0], wh[1]);
        binding.btnPhoto.setLayoutParams(layoutParams);
        binding.btnPhoto.setOnClickListener(this);
        binding.btnVoice.setOnClickListener(this);

        /*********讯飞语音输入*******/
        // 初始化听写Dialog，如果只使用有UI听写功能，无需创建SpeechRecognizer
        // 使用UI听写功能，请根据sdk文件目录下的notice.txt,放置布局文件和图片资源
        mIatDialog = new RecognizerDialog(this, mInitListener);
        // 设置听写引擎
        mIatDialog.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);

        setArea();
        setPId();
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (!GpsUtil.isOPen(mContext)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle("定位服务")
                    .setMessage("定位服务尚未打开，位置获取精度差，是否开启定位服务？")
                    .setPositiveButton("去开启", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //跳转到设置页面让用户自己手动开启
                            Intent locationIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(locationIntent);
                        }
                    }).setNegativeButton("稍候再说", null);
            builder.create().show();
        } else {
            bdLocationManager.start(mContext);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        bdLocationManager.stop();
    }

    private void setArea() {
        countyListViewAdapter = new LabelListViewAdapter(mContext);
        binding.county.setAdapter(countyListViewAdapter);
        binding.county.setOnItemClickListener(this);

        streetListViewAdapter = new LabelListViewAdapter(mContext);
        binding.street.setAdapter(streetListViewAdapter);
        binding.street.setOnItemClickListener(this);
        queryCountyList();
    }

    private void queryCountyList() {
        JSONObject param = new JSONObject();
        param.put("areaid", AppModel.getNingBoAreaID(mContext));
        param.put("areaidByIdentity", AppLoginModel.getAreaId(mContext));
        AppContactsModel.GetNextLevelAreaID(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                countyListViewAdapter.clear();
                countyListViewAdapter.addItems(JSON.parseArray(val));
            }

            @Override
            public void error(String error, String action) {

            }
        });
    }

    private void queryStreetList(final String areaid) {
        JSONObject param = new JSONObject();
        param.put("areaid", areaid);
        param.put("areaidByIdentity", AppLoginModel.getAreaId(mContext));
        AppContactsModel.GetNextLevelAreaID(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                streetListViewAdapter.clear();
                streetListViewAdapter.addItems(JSON.parseArray(val));
            }

            @Override
            public void error(String error, String action) {

            }
        });
    }

    private void setPId() {
        iPIdListViewAdapter = new LabelListViewAdapter(mContext);
        binding.iPId.setAdapter(iPIdListViewAdapter);
        binding.iPId.setOnItemClickListener(this);

        queryIPIdList();
    }

    private void queryIPIdList() {
        AppDissertationModel.GetMenuArr(mContext, null, new BaseListener() {
            @Override
            public void success(String val, String action) {
                iPIdListViewAdapter.clear();
                JSONObject data = JSON.parseObject(val);
                JSONArray array = data.getJSONArray("Data");
                iPIdListViewAdapter.addItems(array);
            }

            @Override
            public void error(String error, String action) {

            }
        });
    }

    private View getImagePartItemRemoveBinding(final String url, int id) {
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(wh[0], wh[1]);
        ImagePartItemRemoveBinding root = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.image_part_item_remove, null, false);
        View view = root.getRoot();
        view.setLayoutParams(layoutParams);
        root.btnRemove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addImages.remove(url);
                resetPhotos();
            }
        });
        root.image.setId(id);
        root.image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TransferConfig config = TransferConfig.build()
                        .setNowThumbnailIndex(v.getId())
                        .setSourceImageList(addImages)
                        .setMissPlaceHolder(R.mipmap.ic_empty_photo)
                        .setOriginImageList(addImageViews)
                        .setProgressIndicator(new ProgressPieIndicator())
                        .setImageLoader(GlideImageLoader.with(mContext.getApplicationContext()))
                        .create();
                transferee.apply(config).show(new Transferee.OnTransfereeStateChangeListener() {
                    @Override
                    public void onShow() {
                        Glide.with(mContext).pauseRequests();
                    }

                    @Override
                    public void onDismiss() {
                        Glide.with(mContext).resumeRequests();
                    }
                });
            }
        });
        addImageViews.add(root.image);
        GlideUtil.loadImgCenterCrop(mContext, url, root.image);

        return view;
    }

    private void resetPhotos() {
        addImageViews.clear();
        View btnPhoto = binding.rectifyImage.getChildAt(binding.rectifyImage.getChildCount() - 1);
        binding.rectifyImage.removeAllViews();
        for (int i = 0, j = addImages.size(); i < j; i++) {
            binding.rectifyImage.addView(getImagePartItemRemoveBinding(addImages.get(i), i));
        }
        binding.rectifyImage.addView(btnPhoto);
    }

    private ImageView getImageView(LinearLayout view) {
        return (ImageView) view.getChildAt(1);
    }

    private void changeVisibility(View view, ImageView arrow) {
        int i = view.getVisibility();
        if (i == View.GONE) {
            view.setVisibility(View.VISIBLE);
            arrow.setImageResource(R.mipmap.arrow_up);
        } else {
            view.setVisibility(View.GONE);
            arrow.setImageResource(R.mipmap.arrow_down);
        }
    }

    @Override
    public void onClick(View view) {
        if (isLoading)
            return;
        switch (view.getId()) {
            case R.id.county_part: {//区县
                changeVisibility(binding.county, getImageView((LinearLayout) view));
                break;
            }
            case R.id.street_part: {//街道
                changeVisibility(binding.street, getImageView((LinearLayout) view));
                break;
            }
            case R.id.i_pId_part: {//专题所属类型
                changeVisibility(binding.iPId, getImageView((LinearLayout) view));
                break;
            }
            case R.id.btn_photo:
                doPhoto();
                break;
            case R.id.btn_voice:
                doVoice();
                break;
            case R.id.btn_add: {
                onSave();
                break;
            }
        }
    }

    private void doPhoto() {
        MultiImageSelector.create()
                .showCamera(true) // show camera or not. true by default
                .count(9) // max select image size, 9 by default. used width #.multi()
                .multi() // multi mode, default mode;
                .start(this, REQUEST_CODE_SELECT);
    }

    private void doVoice() {
        // 显示听写对话框
        mIatDialog.setListener(mRecognizerDialogListener);
        mIatDialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null && requestCode == REQUEST_CODE_SELECT) {
            List<String> images = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            for (int i = 0, j = images.size(); i < j; i++) {
                String item = images.get(i);
                if (!this.addImages.contains(item))
                    this.addImages.add(item);
            }
            resetPhotos();
        }
    }

    @Override
    public void onBackPressed() {
        doCancel();
    }

    private void printResult(RecognizerResult results, boolean isLast) {
        String result = StringUtil.parseIatResult(results.getResultString());
        int index = binding.description.getSelectionStart();//获取光标所在位置
        Editable edit = binding.description.getEditableText();
        if (index < 0 || index >= edit.length()) {
            edit.append(result);
        } else {
            edit.insert(index, result);//光标所在位置插入文字
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        bdLocationManager.stop();
        if (transferee != null)
            transferee.destroy();
    }

    /**
     * 初始化监听器。
     */
    private InitListener mInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
        }
    };

    /**
     * 听写UI监听器
     */
    private RecognizerDialogListener mRecognizerDialogListener = new RecognizerDialogListener() {
        public void onResult(RecognizerResult results, boolean isLast) {
            printResult(results, isLast);
        }

        /**
         * 识别回调错误.
         */
        public void onError(SpeechError error) {
        }
    };

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (parent == binding.county) {
            JSONArray list = countyListViewAdapter.getItems();
            for (int i = 0, j = list.size(); i < j; i++) {
                JSONObject item = (JSONObject) list.get(i);
                item.put("selected", false);
            }
            final JSONObject item = (JSONObject) list.get(position);
            item.put("selected", true);
            countyListViewAdapter.notifyDataSetChanged();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    TextView tv = (TextView) binding.countyPart.getChildAt(0);
                    tv.setText(item.getString("NAME"));
                    tv = (TextView) binding.streetPart.getChildAt(0);
                    tv.setText("街道");
                    changeVisibility(binding.county, (ImageView) binding.countyPart.getChildAt(1));
                }
            }, 32);
            queryStreetList(StringUtil.dTs(item.getString("ID")));
        } else if (parent == binding.street) {
            JSONArray list = streetListViewAdapter.getItems();
            for (int i = 0, j = list.size(); i < j; i++) {
                JSONObject item = (JSONObject) list.get(i);
                item.put("selected", false);
            }
            final JSONObject item = (JSONObject) list.get(position);
            item.put("selected", true);
            streetListViewAdapter.notifyDataSetChanged();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    TextView tv = (TextView) binding.streetPart.getChildAt(0);
                    tv.setText(item.getString("NAME"));
                    changeVisibility(binding.street, (ImageView) binding.streetPart.getChildAt(1));
                }
            }, 32);
        } else if (parent == binding.iPId) {
            JSONArray list = iPIdListViewAdapter.getItems();
            for (int i = 0, j = list.size(); i < j; i++) {
                JSONObject item = (JSONObject) list.get(i);
                item.put("selected", false);
            }
            final JSONObject item = (JSONObject) list.get(position);
            item.put("selected", true);
            iPIdListViewAdapter.notifyDataSetChanged();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    TextView tv = (TextView) binding.iPIdPart.getChildAt(0);
                    tv.setText(item.getString("NAME"));
                    changeVisibility(binding.iPId, (ImageView) binding.iPIdPart.getChildAt(1));
                }
            }, 32);
        }
    }

    private void onSave() {
        imageLoading = false;
        imagePosition = 0;

        paramData = new JSONObject();
        String name = binding.name.getText().toString();
        if (StringUtil.isNull(name)) {
            showMsg("请输入专题名称");
            return;
        }

        paramData.put("name", name);
        Location location = bdLocationManager.getLocation();
        if (location != null) {
            paramData.put("xAxis", StringUtil.getDoubleScale(location.getLongitude(), 8));
            paramData.put("yAxis", StringUtil.getDoubleScale(location.getLatitude(), 8));
        }

        String REGOINID = null;
        JSONArray list = countyListViewAdapter.getItems();
        for (int i = 0, j = list.size(); i < j; i++) {
            JSONObject item = (JSONObject) list.get(i);
            if (item.getBooleanValue("selected")) {
                REGOINID = StringUtil.dTs(item.getString("ID"));
                break;
            }
        }
        if (StringUtil.isNull(REGOINID)) {
            showMsg("请选择区县");
            return;
        }
        String STREETID = null;
        list = streetListViewAdapter.getItems();
        for (int i = 0, j = list.size(); i < j; i++) {
            JSONObject item = (JSONObject) list.get(i);
            if (item.getBooleanValue("selected")) {
                STREETID = StringUtil.dTs(item.getString("ID"));
                break;
            }
        }
        if (StringUtil.isNull(STREETID)) {
            showMsg("请选择街道");
            return;
        }
        paramData.put("townType", STREETID);

        String TADDRESS = binding.TADDRESS.getText().toString();
        if (StringUtil.isNull(TADDRESS)) {
            showMsg("请输入专题详细地址");
            return;
        }
        paramData.put("address", TADDRESS);

        String description = binding.description.getText().toString();
        if (StringUtil.isNull(description)) {
            showMsg("请输入专题描述");
            return;
        }
        paramData.put("description", description);

        String pId = null;
        list = iPIdListViewAdapter.getItems();
        for (int i = 0, j = list.size(); i < j; i++) {
            JSONObject item = (JSONObject) list.get(i);
            if (item.getBooleanValue("selected")) {
                pId = StringUtil.dTs(item.getString("ID"));
                break;
            }
        }
        if (StringUtil.isNull(pId)) {
            showMsg("请选择专题任务类型");
            return;
        }
        paramData.put("pId", pId);
        paramData.put("photoUrl", "");
        paramData.put("identityId", AppLoginModel.getIdentityId(mContext));
        paramData.put("userName", AppLoginModel.getUserName(mContext));

        isLoading = true;
        snackBar = showTSnackbar("正在提交信息..., 请稍候");

        if (!addImages.isEmpty()) {
            imageLoading = true;
            FileUploadModel.upload(mContext, addImages.get(imagePosition), true, this);
            return;
        }

        AppDissertationModel.InsertPoint(mContext, paramData, this);
    }

    @Override
    public void success(String val, String action) {
        if (AppDissertationModel.XCZTHEMATICDATA_INSERTPOINT_ACTION.equals(action)) {
            JSONObject data = JSON.parseObject(val);
            if ("1".equals(data.getString("Result"))) {
                hideTSnackbar(snackBar, "信息保存成功");
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle("信息提交成功");
                builder.setMessage("信息保存成功");
                builder.setCancelable(false);
                builder.setPositiveButton("我知道了", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        setResult(RESULT_OK);
                        finish();
                    }
                });
                builder.show();
            } else {
                isLoading = false;
                hideTSnackbar(snackBar, "信息提交失败，相应参数有错", Prompt.WARNING);
            }
        } else if (FileUploadModel.SMALLTOWN_XCZFILEUPLOAD_SAVEFILE_ACTION.equals(action)) {
            if (imageLoading) {
                JSONObject data = JSON.parseObject(val);
                String photoUrl = paramData.getString("photoUrl");
                StringBuilder sb = new StringBuilder();
                if (!StringUtil.isNull(photoUrl))
                    sb.append(photoUrl).append(",").append(data.getString("FullUrl")).append(",");
                else
                    sb.append(data.getString("FullUrl")).append(",");
                if (sb.lastIndexOf(",") != -1)
                    sb.deleteCharAt(sb.lastIndexOf(","));
                paramData.put("photoUrl", sb.toString());

                if ((imagePosition + 1) >= addImages.size()) {
                    imageLoading = false;
                    AppDissertationModel.InsertPoint(mContext, paramData, this);
                } else {
                    imagePosition++;
                    FileUploadModel.upload(mContext, addImages.get(imagePosition), true, this);
                }
            }
        }
    }

    @Override
    public void error(String error, String action) {
        if (FileUploadModel.SMALLTOWN_XCZFILEUPLOAD_SAVEFILE_ACTION.equals(action)) {
            imageLoading = false;
            FileUploadModel.stop();
            AppDissertationModel.InsertPoint(mContext, paramData, this);
            return;
        }
        isLoading = false;
        hideTSnackbar(snackBar, error, Prompt.WARNING);
    }

    private void doCancel() {
        String msg = "数据尚未提交，您确定要退出吗？";
        if (isLoading)
            msg = "数据正在提交，您确定要退出吗？";
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("温馨提示")
                .setMessage(msg)
                .setPositiveButton("点错了", null)
                .setNegativeButton("退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        FileUploadModel.stop();
                        dialogInterface.dismiss();
                        finish();
                    }
                });
        builder.create().show();
    }
}
